package com.tjjingpan.uibestpratise

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), View.OnClickListener {
    private var msgList =ArrayList<Msg>()
   // private var adapter:MsgAdapter?=null

    lateinit var adapter:MsgAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initMsg()
        val layoutManager = LinearLayoutManager(this)
        recycleView.layoutManager= layoutManager
       // adapter = MsgAdapter(msgList)
        if(!::adapter.isInitialized)  {
            adapter = MsgAdapter(msgList)}
        recycleView.adapter = adapter
        send.setOnClickListener(this)

    }

    private fun initMsg(){
        val msg1 = Msg("Hello guy.",Msg.TYPE_RECEIVED)
        msgList.add(msg1)
        val msg2 = Msg("Hello.Who is that?",Msg.TYPE_SENT)
        msgList.add(msg2)
        val msg3 = Msg("This is Tom,Nice talking to you. ",Msg.TYPE_SENT)
        msgList.add(msg3)


    }

    override fun onClick(v: View?) {
        when(v){
            send ->{
                val content = inputText.text.toString()
                if(content.isNotEmpty()){
                    val msg = Msg(content,Msg.TYPE_SENT)
                    msgList.add(msg)
                    adapter?.notifyItemInserted(msgList.size-1) //当有消息时,刷新RecycleView中的显示
                    recycleView.scrollToPosition(msgList.size-1)//将RecyclerView定位到最后一行
                    inputText.setText("")//清空输入框中的内容
                }
            }
        }
    }
}